package fct.mpc.utils;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class SnipeManager {

	// Database fields
	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;
	private String[] allColumns = { DatabaseHelper.SNIPE_COLUMN_ID,
									DatabaseHelper.SNIPE_COLUMN_NAME,
									DatabaseHelper.SNIPE_COLUMN_ELEMENT,
									DatabaseHelper.SNIPE_COLUMN_HP,
									DatabaseHelper.SNIPE_COLUMN_DEFENSE,
									DatabaseHelper.SNIPE_COLUMN_ATTACK,
									DatabaseHelper.SNIPE_COLUMN_IMAGE,
									DatabaseHelper.SNIPE_COLUMN_USERHUNTED };
	
	public SnipeManager(Context context) {
		this.dbHelper = new DatabaseHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public List<Snipe> getHuntedSnipes() {
		return getSnipeByQuery( DatabaseHelper.SNIPE_COLUMN_USERHUNTED + " > 0" );
	}
	
	public List<Snipe> getAllSnipes() {
		return this.getSnipeByQuery(null);
	}
	
	protected List<Snipe> getSnipeByQuery(String query) {
		List<Snipe> snipeList = new ArrayList<Snipe>();

		Cursor cursor = database.query(DatabaseHelper.SNIPE_TABLE_NAME,
				this.allColumns, query, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Snipe snipe = buildSnipe( cursor );
			snipeList.add( snipe );
			cursor.moveToNext();
		}

		cursor.close();
		return snipeList;
	}
	
	public void setSnipeHunted( String snipeName ) {
		ContentValues updateValue = new ContentValues();
		updateValue.put( DatabaseHelper.SNIPE_COLUMN_USERHUNTED, 1);
		String whereColumn = DatabaseHelper.SNIPE_COLUMN_NAME + " =?";
		String[] whereValue = { snipeName };

		int updatedColumns = database.update( DatabaseHelper.SNIPE_TABLE_NAME, 
						updateValue, 
						whereColumn,
						whereValue);
		
		if( updatedColumns == 0 ) {
			Log.w( "DAO Snipe", 
					"Failure while trying to set the snipe "+snipeName+" as hunted");
		}
	}

	private Snipe buildSnipe(Cursor c) {
		Snipe s = new Snipe();
		s.setId( c.getInt(0) );
		s.setName( c.getString(1) );
		s.setElement( c.getString(2) );
		s.setHealth( c.getInt(3) );
		s.setDefense( c.getInt(4) );
		s.setAttack( c.getInt(5) );
		s.setUserHunted( c.getInt(6) );
		return s;
	}

	
}
